package com.ruoyi.web.controller.report;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.report.domain.Report;
import com.ruoyi.report.domain.ReportData;
import com.ruoyi.report.domain.ServiceItemReport;
import com.ruoyi.report.domain.ServiceLog;
import com.ruoyi.report.service.IReportService;
import com.ruoyi.serve.domain.bo.ServeTaskBo;
import com.ruoyi.serve.domain.vo.ServeTaskVo;
import com.ruoyi.serve.service.IServeTaskItemService;
import com.ruoyi.serve.service.IServeTaskService;
import com.ruoyi.system.domain.vo.SysUserExportVo;
import com.ruoyi.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import lombok.var;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 报表
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/report/")
public class ReportController extends BaseController {

    private final IReportService reportService;


    private final IServeTaskService taskService;

    private final ISysDeptService deptService;

    /**
     * 获取区域服务报表数据列表
     */
    @SaCheckPermission("report:regionservereport:list")
    @GetMapping("/regionServeReportDataList")
    public R<List<ReportData>> ListRegionServeReportData(String month,String status) {
        if(StringUtils.isEmpty(month)){
            month = DateUtils.dateTimeNow("yyyyMM");
        }

        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());


        List<ReportData> dataList = new ArrayList<ReportData>();

        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        deptList.forEach(d->{
            if(d.getParentId() != 0)
            {
                //查询服务任务
                ServeTaskBo taskBo = new ServeTaskBo();
                taskBo.setDeptId(d.getDeptId()+"");
                taskBo.setBeginTime(beginDate);
                taskBo.setEndTime(endDate);
                List<ServeTaskVo> taskVoList = taskService.queryList(taskBo);

                ReportData serviceCountData = new ReportData();
                serviceCountData.setDeptName(d.getDeptName());
                serviceCountData.setTotalCount(taskVoList.size());
                int unbeginCount  = 0;
                int runCount = 0;
                int finishCount = 0;
                for(ServeTaskVo t : taskVoList ){
                    if("0".equals(t.getStatus())){
                        unbeginCount++;
                    }else if("1".equals(t.getStatus())){
                        runCount++;
                    }else if("2".equals(t.getStatus())){
                        finishCount++;
                    }
                }
                serviceCountData.setUnbeginCount(unbeginCount);
                serviceCountData.setRunCount(runCount);
                serviceCountData.setFinishCount(finishCount);
                serviceCountData.setExpireCount(0);
                dataList.add(serviceCountData);

            }

        });

        //Report report = reportService.getRegionServeReport(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate),DateUtils.parseDateToStr("yyyy-MM-dd",endDate),status);
        return R.ok(dataList);
    }

    /**
     * 导出区域服务报表
     */
    @Log(title = "导出区域服务报表", businessType = BusinessType.EXPORT)
    @SaCheckPermission("report:regionservereport:export")
    @PostMapping("/exportRegionServeReport")
    public void regionServeReportDataExport(String month,String status, HttpServletResponse response) {
        if(StringUtils.isEmpty(month)){
            month = DateUtils.dateTimeNow("yyyyMM");
        }

        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());

        Report report  = reportService.getRegionServeReport(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate),
                DateUtils.parseDateToStr("yyyy-MM-dd",endDate),status);
        ExcelUtil.exportExcel(report.getDataList(), report.getReportName(), ReportData.class, response);
    }

    /**
     * 获取服务记录
     */
    @SaCheckPermission("report:servicelog:list")
    @GetMapping("/listServiceLog")
    public TableDataInfo<ServiceLog> listServiceLog(ServiceLog serviceLog, PageQuery pageQuery) {
        String month = serviceLog.getMonth();
        if(StringUtils.isEmpty(serviceLog.getMonth())){
            month = DateUtils.dateTimeNow("yyyyMM");
        }
        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).plusDays(1).atStartOfDay().atZone(zone).toInstant());
        serviceLog.setBeginTime(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate));
        serviceLog.setEndTime(DateUtils.parseDateToStr("yyyy-MM-dd", endDate));
        return reportService.queryServiceLogPageList(serviceLog, pageQuery);
    }

    /**
     * 导出服务记录
     */
    @Log(title = "导出服务记录", businessType = BusinessType.EXPORT)
    @SaCheckPermission("report:servicelog:export")
    @PostMapping("/exportServiceLog")
    public void exportServiceLog(ServiceLog serviceLog, HttpServletResponse response) {
        String month = serviceLog.getMonth();
        if(StringUtils.isEmpty(serviceLog.getMonth())){
            month = DateUtils.dateTimeNow("yyyyMM");
        }
        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).plusDays(1).atStartOfDay().atZone(zone).toInstant());
        serviceLog.setBeginTime(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate));
        serviceLog.setEndTime(DateUtils.parseDateToStr("yyyy-MM-dd", endDate));
        List<ServiceLog> serviceLogList = reportService.queryServiceLogList(serviceLog);
        ExcelUtil.exportExcel(serviceLogList, "服务记录", ServiceLog.class, response);
    }


    /**
     * 获取服务项目报表数据列表
     */
    @SaCheckPermission("report:serviceitemreport:list")
    @GetMapping("/serviceItemReportList")
    public R<List<ServiceItemReport>> ListServiceItem(String month) {
        if(StringUtils.isEmpty(month)){
            month = DateUtils.dateTimeNow("yyyyMM");
        }

        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());

        return R.ok(reportService.getServiceItemReport(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate),DateUtils.parseDateToStr("yyyy-MM-dd",endDate)));
    }


    /**
     * 导出服务项目服务次数
     */
    @Log(title = "导出服务记录", businessType = BusinessType.EXPORT)
    @SaCheckPermission("report:serviceitemreport:export")
    @PostMapping("/exportserviceItem")
    public void exportserviceItem(String month, HttpServletResponse response) {
        if(StringUtils.isEmpty(month)){
            month = DateUtils.dateTimeNow("yyyyMM");
        }

        var localDate = LocalDate.parse(month + "01",DateTimeFormatter.BASIC_ISO_DATE);
        ZoneId zone = ZoneId.systemDefault();
        Date beginDate = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay().atZone(zone).toInstant());
        Date endDate = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay().atZone(zone).toInstant());


        List<ServiceItemReport> list =  reportService.getServiceItemReport(DateUtils.parseDateToStr("yyyy-MM-dd",beginDate),DateUtils.parseDateToStr("yyyy-MM-dd",endDate));
        ExcelUtil.exportExcel(list, "各服务项目服务次数", ServiceItemReport.class, response);
    }


}
